package com.wxit.limit.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.time.Duration;

public class CaffeineTest {

    public static void main(String[] args) throws InterruptedException {
        Cache<String, String> cache = Caffeine.newBuilder().build();
        cache.put("xiaohao", "wujie");

        //先查缓存
        String xiaohao = cache.getIfPresent("xiaohao");
        System.out.println("xiaohao" + xiaohao);

        //没找到的话，返回一个新的值
        String liqin = cache.get("heiehi", key -> {
            return "李沁";
        });
        System.out.println(liqin);

        evicByNum();

        evicByTime();
    }

    @SuppressWarnings("all")
    private static void evicByNum() throws InterruptedException {

        //创建缓存对象
        Cache<String, String> cache = Caffeine.newBuilder()
                //设置缓存大小上限
                .maximumSize(1)
                .build();

        //存数据
        cache.put("a", "wujie");
        cache.put("b", "xiaohao");
        cache.put("c", "liqin");

        //延迟10ms,给清理线程一点时间
        Thread.sleep(10L);

        System.out.println("a的数据为： " + cache.getIfPresent("a"));
        System.out.println("b的数据为： " + cache.getIfPresent("b"));
        System.out.println("c的数据为： " + cache.getIfPresent("c"));
    }


    @SuppressWarnings("all")
    public static void evicByTime() throws InterruptedException {
        Cache<Object, Object> cache = Caffeine.newBuilder()
                //设置缓存有效时间为1s
                .expireAfterWrite(Duration.ofSeconds(1))
                .build();

        //存数据
        cache.put("a", "xiaohao");

        //获取数据
        System.out.println("a的数据是：" + cache.getIfPresent("a"));

        //休眠一会
        Thread.sleep(1200L);
        System.out.println("a的数据是：" + cache.getIfPresent("a"));
    }

}
